<script setup lang="ts">
import { postPasswordAPI } from '@/apis/common'
import type { PostLoginPasswordParams } from '@/types/common'
import { useUserStore } from '@/stores/user'
import { ref } from 'vue'

defineOptions({
  options: {
    styleIsolation: 'shared',
  },
})

// 1. 获取表单数据
const formDara = ref<PostLoginPasswordParams>({
  // 13230000082   abc12345
  mobile: '13230000051',
  password: 'abc12345',
})
// 2. 表单校验
const formRules = ref<UniHelper.UniFormsRules>({
  mobile: {
    rules: [
      { required: true, errorMessage: '请输入手机号' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '请输入正确的手机号' },
    ],
  },
  password: {
    rules: [
      { required: true, errorMessage: '请输入密码' },
      { pattern: /^[a-zA-Z0-9]{6,20}$/, errorMessage: '请输入正确的密码' },
    ],
  },
})

// 3. 点击登录校验整个表格
const formRef = ref<UniHelper.UniFormsInstance>()
const isAgree = ref(false)
// 4. 登录
const handleLogin = async () => {
  if (!isAgree.value) {
    return uni.showToast({ title: '请同意用户协议和隐私协议', icon: 'none' })
  }
  formRef.value?.validate?.()
  // 发送表单给后端，获取登录结果
  const res = await postPasswordAPI(formDara.value)
  // console.log('登录结果', res)
  // 获取token
  const store = useUserStore()
  store.setToken(res.data.token)
  // 请提示
  uni.showToast({ title: '登录成功', icon: 'success' })
  // 跳转至首页
  uni.switchTab({ url: '/pages/index/index' })
}
</script>

<template>
  <uni-forms class="login-form" ref="formRef" :model="formDara" :rules="formRules">
    <uni-forms-item name="mobile">
      <uni-easyinput
        :maxlength="11"
        v-model="formDara.mobile"
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <uni-easyinput
        :maxlength="20"
        v-model="formDara.password"
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="false" color="#16C2A3" @tap="isAgree = !isAgree" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @tap="handleLogin">登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" "> 忘记密码？ </navigator>
  </uni-forms>
</template>

<style lang="scss">
@import './styles.scss';
</style>
